//
//  WBNewFeatureView.swift
//  ZWWEIBO
//
//  Created by xzw on 2018/4/8.
//  Copyright © 2018年 xzw. All rights reserved.
//

import UIKit

class WBNewFeatureView: UIView {

    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var pageControl: UIPageControl!
    
    @IBOutlet weak var enterWBBtn: UIButton!
    
    class func loadNewFeatureView() -> WBNewFeatureView{
        
        let nib = UINib(nibName: "WBNewFeatureView", bundle: nil)
        let view = nib.instantiate(withOwner: nil, options: nil)[0] as! WBNewFeatureView
        
        //设置满屏加载,默认600*600
        view.frame = UIScreen.main.bounds
        
        return view
    }
    
    //自动布局视图大小默认是600*600
    override func awakeFromNib() {
     
        let count = 4 //新特性图片张数
        let rect = UIScreen.main.bounds
        for i in 0..<count  {
            
            let imgName = "new_feature_\(i+1)"
            let imgView = UIImageView(image: UIImage(named: imgName))
            imgView.frame = rect.offsetBy(dx:CGFloat(i) * rect.width, dy: 0)
            scrollView.addSubview(imgView)
        }
        
        scrollView.contentSize = CGSize(width: rect.width * CGFloat(count + 1), height: 0)
        scrollView.isPagingEnabled = true
        scrollView.bounces = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        scrollView.delegate = self
        
        enterWBBtn.isHidden = true
    }
    
    //进入微博
    @IBAction func enterWeiBo(_ sender: UIButton) {
        removeFromSuperview()
    }
}

extension WBNewFeatureView : UIScrollViewDelegate {
    
    //停止减速
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let page = Int(scrollView.contentOffset.x / UIScreen.main.bounds.width)
        
        enterWBBtn.isHidden = (page != scrollView.subviews.count - 1)
        //是否是最后一页
        if page == scrollView.subviews.count {
            removeFromSuperview() 
        }
    }
    
    //滚动
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        enterWBBtn.isHidden = true
        
        //便宜量
        let page = Int(scrollView.contentOffset.x / UIScreen.main.bounds.width + 0.5)
        
        //设置pageControl
        pageControl.currentPage = page
        pageControl.isHidden = (page == scrollView.subviews.count)
    }
    
}
